import strCompanyJobPageHtml from "./CompanyJobPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { companyJobService } from "../../services/companyJobService.js";
import { jobApplicationService } from "../../services/jobApplicationService.js";
import { userService } from "../../services/userService.js";

export class CompanyJobPage {
  constructor() {
    this.currentPage = 1;
    this.pageSize = 10;
    this.searchKeyword = "";
    this.searchType = "id";
    this.totalPages = 0;
    this.totalItems = 0;
    this.selectedJobs = new Set();
    this.applyModal = null;
    this.applyModalInstance = null;
  }

  render() {
    const dom = DomUtils.convertToDom(strCompanyJobPageHtml);
    this._bindElements(dom);
    this._bindEvents(dom);
    this._loadData();
    return dom;
  }

  _bindElements(dom) {
    this.searchTypeSelect = dom.querySelector("#searchType");
    this.searchInput = dom.querySelector("#searchInput");
    this.searchBtn = dom.querySelector("#searchBtn");
    this.addJobBtn = dom.querySelector("#addJobBtn");
    this.batchDeleteBtn = dom.querySelector("#batchDeleteBtn");
    this.selectAllCheckbox = dom.querySelector("#selectAll");
    this.jobTableBody = dom.querySelector("#jobTableBody");
    this.pagination = dom.querySelector("#pagination");
    this.jobModal = dom.querySelector("#jobModal");
    this.jobForm = dom.querySelector("#jobForm");
    this.modalClose = dom.querySelector("#modalClose");
    this.jobId = dom.querySelector("#jobId");
    this.jobTitle = dom.querySelector("#jobTitle");
    this.companyName = dom.querySelector("#companyName");
    this.jobType = dom.querySelector("#jobType");
    this.companyEmail = dom.querySelector("#companyEmail");
    this.contactPerson = dom.querySelector("#contactPerson");
    this.contactPhone = dom.querySelector("#contactPhone");
    this.hireNumber = dom.querySelector("#hireNumber");
    this.salaryRange = dom.querySelector("#salaryRange");
    this.workLocation = dom.querySelector("#workLocation");
    this.jobRequirements = dom.querySelector("#jobRequirements");
    this.applyModal = dom.querySelector("#applyModal");
    this.applyForm = dom.querySelector("#applyForm");
    this.cardHeader = dom.querySelector(".card-header");
  }

  _bindEvents(dom) {
    // 搜索按钮点击事件
    this.searchBtn?.addEventListener("click", async () => {
      const searchValue = this.searchInput.value.trim();
      const searchType = this.searchTypeSelect.value;

      if (!searchValue) {
        this._showError("请输入搜索内容");
        return;
      }

      try {
        let jobs;
        if (searchType === "id") {
          const id = parseInt(searchValue);
          if (isNaN(id)) {
            this._showError("请输入有效的招聘信息ID");
            return;
          }
          const job = await companyJobService.getCompanyJob(id);
          jobs = job ? [job] : [];
        } else {
          // 获取所有招聘信息并在前端进行模糊匹配
          const allJobs = await companyJobService.getCompanyJobs(1, 1000);
          jobs = allJobs.items.filter((job) => {
            const searchText = searchValue.toLowerCase();
            if (searchType === "jobTitle") {
              return (job.jobTitle || "").toLowerCase().includes(searchText);
            } else if (searchType === "companyName") {
              return (job.companyName || "").toLowerCase().includes(searchText);
            } else if (searchType === "companyEmail") {
              return (job.companyEmail || "")
                .toLowerCase()
                .includes(searchText);
            }
            return false;
          });
        }

        if (jobs.length > 0) {
          this._renderTable(jobs);
          this._hidePagination();
          this._addBackButton();
        } else {
          this._showError(
            `未找到${
              searchType === "id"
                ? "招聘信息ID"
                : searchType === "jobTitle"
                ? "岗位名称"
                : searchType === "companyName"
                ? "企业名称"
                : "企业邮箱"
            }包含 "${searchValue}" 的招聘信息`
          );
        }
      } catch (error) {
        console.error("Error searching company jobs:", error);
        this._showError("查询失败：" + error.message);
      }
    });

    // 搜索输入框回车事件
    this.searchInput?.addEventListener("keypress", (e) => {
      if (e.key === "Enter") this.searchBtn.click();
    });

    // 分页点击
    this.pagination?.addEventListener("click", (e) => {
      e.preventDefault();
      if (e.target.tagName === "A") {
        this.currentPage = parseInt(e.target.dataset.page);
        this._loadData();
      }
    });

    // 新增职位按钮点击事件
    this.addJobBtn?.addEventListener("click", () => this._showAddModal());

    // 批量删除按钮点击事件
    this.batchDeleteBtn?.addEventListener("click", () =>
      this._handleBatchDelete()
    );

    // 全选/取消全选
    this.selectAllCheckbox?.addEventListener("change", (e) =>
      this._handleSelectAll(e)
    );

    // 表单提交
    this.jobForm?.addEventListener("submit", (e) => this._handleFormSubmit(e));

    // 模态框关闭按钮
    this.modalClose?.addEventListener("click", () => this._hideModal());

    // 表格操作
    this.jobTableBody?.addEventListener("click", async (e) => {
      const btn = e.target.closest("button");
      if (!btn) return;

      const id = btn.dataset.id;
      if (btn.classList.contains("delete-btn")) {
        if (confirm("确认删除该职位？")) {
          await companyJobService.deleteJob(id);
          this._loadData();
        }
      } else if (btn.classList.contains("edit-btn")) {
        await this._showEditModal(id);
      } else if (btn.classList.contains("apply-btn")) {
        await this._showApplyModal(id);
      }
    });

    // 投递简历表单提交
    this.applyForm?.addEventListener("submit", async (e) => {
      e.preventDefault();
      await this._handleApplyFormSubmit();
    });

    // 投递简历模态框关闭按钮
    dom.querySelector("#applyModalClose")?.addEventListener("click", () => {
      this._cleanupApplyModal();
    });
  }

  async _loadData() {
    try {
      const response = await companyJobService.getCompanyJobs(
        this.currentPage,
        this.pageSize,
        this.searchType,
        this.searchKeyword
      );

      const items = Array.isArray(response.items) ? response.items : [];
      this.totalItems = response.total || items.length;
      this.totalPages =
        response.totalPages || Math.ceil(this.totalItems / this.pageSize);

      this._renderTable(items);
      this._renderPagination();
    } catch (error) {
      console.error("Error loading company jobs:", error);
      this._showError("加载招聘信息失败");
    }
  }

  _renderTable(jobs) {
    if (!Array.isArray(jobs)) {
      console.error("Invalid jobs data:", jobs);
      this._showError("数据格式错误");
      return;
    }

    this.jobTableBody.innerHTML = "";
    jobs.forEach((job) => {
      const row = document.createElement("tr");
      row.innerHTML = `
        <td>
          <div class="custom-checkbox custom-control">
            <input
              type="checkbox"
              class="custom-control-input"
              id="select-${job.id}"
              data-id="${job.id}"
            />
            <label for="select-${job.id}" class="custom-control-label"></label>
          </div>
        </td>
        <td>${job.id || "-"}</td>
        <td>${job.jobTitle || "-"}</td>
        <td>${job.companyName || "-"}</td>
        <td>${job.jobType || "-"}</td>
        <td>${job.hireNumber || "-"}</td>
        <td>${job.salaryRange || "-"}</td>
        <td>${job.workLocation || "-"}</td>
        <td>
          <button class="btn btn-info btn-sm detail-btn" data-id="${job.id}">
            <i class="fas fa-eye"></i> 详情
          </button>
          <button class="btn btn-primary btn-sm edit-btn" data-id="${job.id}">
            <i class="fas fa-edit"></i> 编辑
          </button>
          <button class="btn btn-success btn-sm apply-btn" data-id="${job.id}">
            <i class="fas fa-paper-plane"></i> 投递简历
          </button>
          <button class="btn btn-danger btn-sm delete-btn" data-id="${job.id}">
            <i class="fas fa-trash"></i> 删除
          </button>
        </td>
      `;
      this.jobTableBody.appendChild(row);

      const detailBtn = row.querySelector(".detail-btn");
      const editBtn = row.querySelector(".edit-btn");
      const applyBtn = row.querySelector(".apply-btn");
      const deleteBtn = row.querySelector(".delete-btn");
      const checkbox = row.querySelector(`#select-${job.id}`);

      detailBtn.addEventListener("click", () => this._showDetailModal(job.id));
      editBtn.addEventListener("click", () => this._showEditModal(job.id));
      applyBtn.addEventListener("click", () => this._showApplyModal(job.id));
      deleteBtn.addEventListener("click", () => this._handleDelete(job.id));
      checkbox.addEventListener("change", (e) => this._handleSelect(e, job.id));
    });

    if (jobs.length === 0) {
      this._showNoData();
    }
  }

  _renderPagination() {
    let startPage = Math.max(1, this.currentPage - 2);
    let endPage = Math.min(this.totalPages, startPage + 4);

    if (endPage - startPage < 4) {
      startPage = Math.max(1, endPage - 4);
    }

    let pages = [];

    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="1" title="首页">
          <i class="fas fa-angle-double-left"></i>
        </a>
      </li>
    `);

    pages.push(`
      <li class="page-item ${this.currentPage === 1 ? "disabled" : ""}">
        <a class="page-link" href="#" data-page="${
          this.currentPage - 1
        }" title="上一页">
          <i class="fas fa-angle-left"></i>
        </a>
      </li>
    `);

    for (let i = startPage; i <= endPage; i++) {
      pages.push(`
        <li class="page-item ${i === this.currentPage ? "active" : ""}">
          <a class="page-link" href="#" data-page="${i}">${i}</a>
        </li>
      `);
    }

    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.currentPage + 1
        }" title="下一页">
          <i class="fas fa-angle-right"></i>
        </a>
      </li>
    `);

    pages.push(`
      <li class="page-item ${
        this.currentPage === this.totalPages ? "disabled" : ""
      }">
        <a class="page-link" href="#" data-page="${
          this.totalPages
        }" title="末页">
          <i class="fas fa-angle-double-right"></i>
        </a>
      </li>
    `);

    this.pagination.innerHTML = pages.join("");
  }

  _showAddModal() {
    this.jobId.value = "";
    this.jobForm.reset();
    this.jobModal.classList.add("show");
    this.jobModal.style.display = "block";
  }

  async _showEditModal(id) {
    try {
      const job = await companyJobService.getCompanyJob(id);
      this.jobId.value = job.id;
      this.jobTitle.value = job.jobTitle;
      this.companyName.value = job.companyName;
      this.jobType.value = job.jobType;
      this.companyEmail.value = job.companyEmail;
      this.contactPerson.value = job.contactPerson;
      this.contactPhone.value = job.contactPhone;
      this.hireNumber.value = job.hireNumber;
      this.salaryRange.value = job.salaryRange;
      this.workLocation.value = job.workLocation;
      this.jobRequirements.value = job.jobRequirements;
      this.jobModal.classList.add("show");
      this.jobModal.style.display = "block";
    } catch (error) {
      console.error("Error loading job:", error);
      alert("加载招聘信息失败");
    }
  }

  async _showDetailModal(id) {
    try {
      const job = await companyJobService.getCompanyJob(id);
      const modal = document.createElement("div");
      modal.className = "modal fade";
      modal.id = "detailModal";
      modal.innerHTML = `
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">招聘信息详情</h5>
              <button type="button" class="close" data-dismiss="modal">
                <span>&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="row">
                <div class="col-md-6">
                  <p><strong>ID:</strong> ${job.id || "-"}</p>
                  <p><strong>招聘岗位:</strong> ${job.jobTitle || "-"}</p>
                  <p><strong>企业名称:</strong> ${job.companyName || "-"}</p>
                  <p><strong>工作类型:</strong> ${job.jobType || "-"}</p>
                  <p><strong>企业邮箱:</strong> ${job.companyEmail || "-"}</p>
                </div>
                <div class="col-md-6">
                  <p><strong>联系人:</strong> ${job.contactPerson || "-"}</p>
                  <p><strong>联系电话:</strong> ${job.contactPhone || "-"}</p>
                  <p><strong>招聘人数:</strong> ${job.hireNumber || "-"}</p>
                  <p><strong>薪资待遇:</strong> ${job.salaryRange || "-"}</p>
                  <p><strong>工作地点:</strong> ${job.workLocation || "-"}</p>
                </div>
              </div>
              <div class="row mt-3">
                <div class="col-12">
                  <p><strong>职位要求:</strong></p>
                  <div class="border p-2">${job.jobRequirements || "-"}</div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
            </div>
          </div>
        </div>
      `;

      document.body.appendChild(modal);
      const modalInstance = new bootstrap.Modal(modal);
      modalInstance.show();

      modal.addEventListener("hidden.bs.modal", () => {
        modal.remove();
      });
    } catch (error) {
      console.error("Error loading job details:", error);
      alert("加载招聘信息详情失败");
    }
  }

  _hideModal() {
    this.jobModal.classList.remove("show");
    this.jobModal.style.display = "none";
  }

  async _handleFormSubmit(e) {
    e.preventDefault();
    const formData = {
      jobTitle: this.jobTitle.value,
      companyName: this.companyName.value,
      jobType: this.jobType.value,
      companyEmail: this.companyEmail.value,
      contactPerson: this.contactPerson.value,
      contactPhone: this.contactPhone.value,
      hireNumber: parseInt(this.hireNumber.value) || 1,
      salaryRange: this.salaryRange.value,
      workLocation: this.workLocation.value,
      jobRequirements: this.jobRequirements.value,
    };

    try {
      if (this.jobId.value) {
        await companyJobService.updateCompanyJob(this.jobId.value, formData);
        alert("更新成功");
      } else {
        await companyJobService.createCompanyJob(formData);
        alert("创建成功");
      }
      this._hideModal();
      this._loadData();
    } catch (error) {
      console.error("Error saving job:", error);
      alert("保存失败");
    }
  }

  async _handleDelete(id) {
    if (!confirm("确定要删除这个招聘信息吗？")) return;

    try {
      await companyJobService.deleteCompanyJob(id);
      alert("删除成功");
      this._loadData();
    } catch (error) {
      console.error("Error deleting job:", error);
      alert("删除失败");
    }
  }

  _handleSelectAll(e) {
    const checkboxes = this.jobTableBody.querySelectorAll(
      "input[type='checkbox']"
    );
    checkboxes.forEach((checkbox) => {
      checkbox.checked = e.target.checked;
      const id = checkbox.dataset.id;
      if (e.target.checked) {
        this.selectedJobs.add(id);
      } else {
        this.selectedJobs.delete(id);
      }
    });
    this.batchDeleteBtn.disabled = this.selectedJobs.size === 0;
  }

  _handleSelect(e, id) {
    if (e.target.checked) {
      this.selectedJobs.add(id);
    } else {
      this.selectedJobs.delete(id);
    }
    this.batchDeleteBtn.disabled = this.selectedJobs.size === 0;
  }

  async _handleBatchDelete() {
    if (this.selectedJobs.size === 0) return;
    if (!confirm(`确定要删除选中的 ${this.selectedJobs.size} 个招聘信息吗？`))
      return;

    try {
      await companyJobService.batchDeleteCompanyJobs(
        Array.from(this.selectedJobs)
      );
      alert("批量删除成功");
      this.selectedJobs.clear();
      this.selectAllCheckbox.checked = false;
      this.batchDeleteBtn.disabled = true;
      this._loadData();
    } catch (error) {
      console.error("Error batch deleting jobs:", error);
      alert("批量删除失败");
    }
  }

  _addBackButton() {
    // 如果返回按钮已经存在，先移除它
    const existingBackButton =
      this.searchBtn.parentNode.querySelector(".btn-secondary");
    if (existingBackButton) {
      existingBackButton.remove();
    }

    // 添加返回按钮
    const backButton = document.createElement("button");
    backButton.className = "btn btn-secondary btn-sm ml-2";
    backButton.innerHTML = '<i class="fas fa-arrow-left"></i> 返回列表';
    backButton.onclick = () => {
      this._loadData();
      backButton.remove();
    };

    this.searchBtn.parentNode.insertBefore(
      backButton,
      this.searchBtn.nextSibling
    );
  }

  _showError(message) {
    this.jobTableBody.innerHTML = `
      <tr><td colspan="11" class="text-center text-danger">${message}</td></tr>
    `;
    this._addBackButton();
  }

  _showNoData() {
    this.jobTableBody.innerHTML = `
      <tr>
        <td colspan="9" class="text-center">
          暂无数据
        </td>
      </tr>
    `;
  }

  _hidePagination() {
    this.pagination.classList.add("d-none");
  }

  _showPagination() {
    this.pagination.classList.remove("d-none");
  }

  async _showApplyModal(jobId) {
    try {
      const job = await companyJobService.getCompanyJob(jobId);
      if (!job) {
        throw new Error("未找到该职位信息");
      }

      const form = this.applyForm;
      form.querySelector("#jobId").value = job.id;
      form.querySelector("#companyName").value = job.companyName;
      form.querySelector("#jobTitle").value = job.jobTitle;
      form.querySelector("#jobType").value = job.jobType;

      if (!this.applyModalInstance) {
        this.applyModalInstance = new bootstrap.Modal(this.applyModal, {
          backdrop: "static",
        });

        this.applyModal.addEventListener("hidden.bs.modal", () => {
          this.applyModalInstance = null;
        });
      }

      this.applyModalInstance.show();
    } catch (error) {
      console.error("Error loading job details:", error);
      alert("加载职位信息失败：" + error.message);
    }
  }

  _cleanupApplyModal() {
    if (this.applyModalInstance) {
      this.applyModalInstance.hide();
    }
    this.applyForm.reset();
  }

  async _handleApplyFormSubmit() {
    const form = this.applyForm;
    if (!form.checkValidity()) {
      form.classList.add("was-validated");
      return;
    }

    // 获取并验证表单数据
    const jobId = parseInt(form.querySelector("#jobId").value);
    const seekerName = form.querySelector("#seekerName").value.trim();
    const seekerPhone = form.querySelector("#seekerPhone").value.trim();
    const seekerEmail = form.querySelector("#seekerEmail").value.trim();
    const companyName = form.querySelector("#companyName").value.trim();
    const jobTitle = form.querySelector("#jobTitle").value.trim();
    const jobType = form.querySelector("#jobType").value.trim();

    if (!jobId || isNaN(jobId)) {
      alert("无效的职位ID");
      return;
    }

    if (!seekerName) {
      alert("请输入求职者姓名");
      return;
    }

    if (!seekerPhone) {
      alert("请输入求职者电话");
      return;
    }

    if (!seekerEmail) {
      alert("请输入求职者邮箱");
      return;
    }

    if (!companyName) {
      alert("企业名称不能为空");
      return;
    }

    if (!jobTitle) {
      alert("职位名称不能为空");
      return;
    }

    if (!jobType) {
      alert("工作类型不能为空");
      return;
    }

    try {
      // 获取职位详细信息以获取联系人电话
      const job = await companyJobService.getCompanyJob(jobId);
      if (!job || !job.contactPhone) {
        throw new Error("无法获取职位联系人信息");
      }

      const formData = {
        jobSeekerId: 1, // 临时使用一个固定的求职者ID
        companyJobId: jobId,
        companyName: companyName,
        jobTitle: jobTitle,
        jobType: jobType,
        contactPhone: job.contactPhone, // 使用职位信息中的联系人电话
        seekerName: seekerName,
        seekerPhone: seekerPhone,
        seekerEmail: seekerEmail,
        applicationDate: new Date().toISOString(),
        applicationStatus: "PENDING",
      };

      console.log(
        "Submitting job application with data:",
        JSON.stringify(formData, null, 2)
      );
      const response = await jobApplicationService.createJobApplication(
        formData
      );
      console.log("Job application response:", response);

      if (response) {
        alert("简历投递成功！");
        this._cleanupApplyModal();
      } else {
        throw new Error("创建求职申请失败：服务器未返回响应");
      }
    } catch (error) {
      console.error("Error submitting application:", error);
      let errorMessage = "简历投递失败：";

      if (error.response) {
        // 处理服务器返回的错误
        const errorData = error.response.data;
        console.error("Server error details:", errorData);
        errorMessage += errorData.message || errorData.error || "服务器错误";
      } else if (error.request) {
        // 处理请求错误
        console.error("Request error:", error.request);
        errorMessage += "网络请求失败，请检查网络连接";
      } else {
        // 处理其他错误
        console.error("Error details:", error);
        errorMessage += error.message || "未知错误";
      }

      alert(errorMessage);
    } finally {
      form.classList.remove("was-validated");
    }
  }
}
